#!/bin/sh
# Bug reports and comments to Igor.Ermolaev@intel.com
source $(dirname $(readlink -f ${BASH_SOURCE[0]:-$0}))/find_loop
precond=precond.$isa.tbz2
if [ ! -r $precond ]; then
   echo >&2
   echo Error: Please, create pre-conditioner first. >&2
   echo >&2
   exit
fi
spth=path.$isa.s
tpth=path.$isa.tbz2
mv $precond $tpth

pcnt=`tar tfj $tpth --wildcards '*.p*[0-9].s'|wc -l`
if [ -z "$pcnt" ] || [ $pcnt == '0' ]; then
   echo >&2
   echo Error: Empty pre-conditioner. >&2
   echo >&2
   exit
fi

plst=( `seq 1 $((pcnt-4))` )

a0=`tar xfjO $tpth --wildcards '*.p'$((pcnt-2))'.s'|$base/get_ranges -r|awk '{print $2}'`
a1=`tar xfjO $tpth --wildcards '*.p'$((pcnt-3))'.s'|$base/get_ranges -r|awk '{print $2}'`
if [ "$a0" != "$a1" ]; then plst[${#plst}]=$((pcnt-2)); fi

pidx=0
for p in ${plst[@]}; do
   ((pidx++))
   asrc=`tar tfj $tpth --wildcards '*.p'$p'.s'`
   tar xfj $tpth $asrc
   anchor=${asrc/%.p$p.s/.p$pidx.s};[ "$asrc" != "$anchor" ] && mv $asrc $anchor
   if [ $pidx -eq 1 ]; then mode=c; else mode=a; fi
   tar ${mode}f precond.$isa.tar $anchor
done
if [ $pidx -gt 0 ]; then bzip2 --best precond.$isa.tar;mv precond.$isa.tar.bz2 $precond; fi

echo "; dependencies: $tpth" >$spth
tar xfjO $tpth --wildcards '*.p'$((pcnt-2))'.s'|$base/get_path 4 0 -b >>$spth
echo ';-------------------------------------------------------' >>$spth
tar xfjO $tpth --wildcards '*.p'$((pcnt-3))'.s'|$base/get_path 0 1 >>$spth
echo '...' >>$spth
tar xfjO $tpth --wildcards '*.p'$((pcnt-0))'.s'|$base/get_path 0 0 -b >>$spth
echo '...' >>$spth
tar xfjO $tpth --wildcards '*.p'$((pcnt-1))'.s'|$base/get_path 0 0 -b >>$spth
echo ';-------------------------------------------------------' >>$spth
tar xfjO $tpth --wildcards '*.p'$((pcnt-0))'.s'|$base/get_path 0 5 >>$spth
echo ';=======================================================' >>$spth

module=`tar xfjO $tpth --wildcards '*.p'$((pcnt-3))'.s'|tail -n 1|sed -n 's/^.*\s-moi\s\(\S\+\).*$/\1/p'`

save_IFS=$IFS;IFS='
';ranges=( `$base/get_ranges -r <$spth` )
for r in ${ranges[@]}; do
   save_IFS2=$IFS;IFS=' ';range=( $r );IFS=$save_IFS2
   echo
   echo 'First, try do whole path tracing using the following command.'
   echo
   echo '   'sde ${tgt:+$tgt }-pinlit -trace-mt -start-address ${range[1]} -stop-address ${range[2]}:1 -length 100000000 ${extra:+$extra }-moi $(basename $module) -- '$@'
   echo
   echo 'If number of instructions in trace is  less than 30M, choose'
   echo 'appropriate  skip  count  for  -stop-address  to get  30-70M'
   echo 'instructions in trace.'
   echo
   if [ "${range[1]}" != "-1" ]; then
      echo "If you'd  like  to  skip  several  path  instances  use  the"
      echo 'following command:'
      echo
      echo '   'sde ${tgt:+$tgt }-pinlit -trace-mt -start-address ${range[1]}:1 -stop-address ${range[2]}:1 -length 100000000 ${extra:+$extra }-moi $(basename $module) -- '$@'
      echo
   fi
   break 2
done
IFS=$save_IFS
